package com.chen.paymentdemo.config;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.ScheduledUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;


@Configuration
@PropertySource("classpath:wxpay.properties") //读取配置文件
@ConfigurationProperties(prefix="wxpay") //读取wxpay节点
@Data //使用set方法将wxpay节点中的值填充到当前类的属性中
@Slf4j
public class WxPayConfig {

    // 商户号
    private String mchId;

    // 商户API证书序列号
    private String mchSerialNo;

    // 商户私钥文件
    private String privateKeyPath;

    // APIv3密钥
    private String apiV3Key;

    // APPID
    private String appid;

    // 微信服务器地址
    private String domain;

    // 接收结果通知地址
    private String notifyDomain;

    /**
     *获取商户的私钥文件 用于签名
     * */
   private PrivateKey getPrivateKey(String privateKeyPath) {

        try {
            //加载商户私钥（privateKey：私钥文件输入流）
            return PemUtil.loadPrivateKey(new FileInputStream(privateKeyPath));
        } catch (FileNotFoundException e) {
            throw new RuntimeException("找不到商户私钥文件", e);
        }
    }

    /**
     * 获取签名验证器
     * */
    @Bean
    public ScheduledUpdateCertificatesVerifier getVerifier(){

        log.info("获取签名验证器");


//        //获取商户私钥
//        PrivateKey privateKey = getPrivateKey(privateKeyPath);
//
//        //私钥签名对象
//        PrivateKeySigner privateKeySigner = new PrivateKeySigner(mchSerialNo, getPrivateKey(privateKeyPath));

        //身份认证对象
//        WechatPay2Credentials wechatPay2Credentials = new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, getPrivateKey(privateKeyPath)));

        //使用定时更新的签名验证器，不需要传入证书 自动下载证书
        ScheduledUpdateCertificatesVerifier verifier = new ScheduledUpdateCertificatesVerifier(
                //商户号、商户证书序列号、商户私钥
                new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, getPrivateKey(privateKeyPath))),
                apiV3Key.getBytes(StandardCharsets.UTF_8) // APIv3密钥.getBytes(StandardCharsets.UTF_8) 对称密钥
        );
        return verifier;
    }


    /**
     * 获取Http请求对象
     * */
    @Bean
   public CloseableHttpClient getWxPayClient(ScheduledUpdateCertificatesVerifier verifier) {

        log.info("获取HttpClient请求对象");

        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, getPrivateKey(privateKeyPath))// 商户号、商户证书序列号、商户私钥
                .withValidator(new WechatPay2Validator(verifier)); // 验证签名的方法，这里是使用WechatPay2Validator来实现的
        //接下来，你任然可以通过builder设置各种参数，来配置你的HttpClient

        //通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签，并进行证书的自动更新
        CloseableHttpClient httpClient = builder.build();

//        //后面跟使用Apache HttpClient一样使用即可
//        CloseableHttpResponse response = httpClient.execute(request);


       return httpClient;

    }

}
